import { useSocketStore } from '@/store/modules/socket';
import { useUserStore } from '@/store/modules/user';
import { ElNotification } from 'element-plus';
import type { NotificationMessage, MessageHandler } from './types';

// 通知服务类
export class NotificationService {
  private socketStore = useSocketStore();
  private userStore = useUserStore();
  private messageHandlers: MessageHandler[] = [];
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectInterval = 3000; // 3秒
  private isConnecting = false;

  constructor() {
    this.initWebSocket();
  }

  // 初始化WebSocket连接
  private initWebSocket() {
    if (this.isConnecting) return;
    this.isConnecting = true;
    if (!this.socketStore.isConnectWebSocket) {
      this.socketStore.connectWebSocket();
    }
    this.watchConnectionStatus();
  }

  // 监听连接状态
  private watchConnectionStatus() {
    const checkConnection = () => {
      if (
        !this.socketStore.isConnectWebSocket &&
        this.reconnectAttempts < this.maxReconnectAttempts
      ) {
        this.reconnectAttempts++;
        setTimeout(() => {
          this.socketStore.connectWebSocket();
          this.isConnecting = false;
        }, this.reconnectInterval);
      } else if (this.socketStore.isConnectWebSocket) {
        this.reconnectAttempts = 0;
        this.isConnecting = false;
      }
    };
    setInterval(checkConnection, 5000);
  }

  public addMessageHandler(handler: MessageHandler) {
    this.messageHandlers.push(handler);
  }

  public removeMessageHandler(handler: MessageHandler) {
    const index = this.messageHandlers.indexOf(handler);
    if (index > -1) {
      this.messageHandlers.splice(index, 1);
    }
  }

  public handleMessage(messageData: any) {
    try {
      let parsedMessage: any;
      if (typeof messageData === 'string') {
        parsedMessage = JSON.parse(messageData);
      } else if (messageData.body) {
        parsedMessage = JSON.parse(messageData.body);
      } else {
        parsedMessage = messageData;
      }
      const notificationMessage: NotificationMessage = {
        id: parsedMessage.id || Date.now().toString(),
        type: parsedMessage.type || 'system',
        sender: parsedMessage.sender || '系统',
        content: parsedMessage.content || parsedMessage.message || '收到新消息',
        avatar: parsedMessage.avatar,
        link: parsedMessage.link,
        isRead: false,
        createTime: parsedMessage.createTime || new Date().toISOString(),
        data: parsedMessage.data
      };
      this.messageHandlers.forEach(handler => {
        try {
          handler(notificationMessage);
        } catch (error) {
          console.error('消息处理器执行失败:', error);
        }
      });
      this.showSystemNotification(notificationMessage);
    } catch (error) {
      console.error('处理WebSocket消息失败:', error);
    }
  }

  private showSystemNotification(message: NotificationMessage) {
    let type: 'success' | 'warning' | 'info' | 'error' = 'info';
    let title = message.sender;
    switch (message.type) {
      case 'system':
        type = 'info';
        title = '系统通知';
        break;
      case 'comment':
        type = 'success';
        title = '新评论';
        break;
      case 'like':
        type = 'warning';
        title = '新点赞';
        break;
      case 'follow':
        type = 'success';
        title = '新关注';
        break;
      case 'mention':
        type = 'warning';
        title = '有人@了你';
        break;
    }
    ElNotification({
      title,
      message: message.content,
      type,
      duration: 4000,
      onClick: () => {
        if (message.link) {
          window.open(message.link, '_blank');
        }
      }
    });
  }

  public sendMessage(message: Partial<NotificationMessage>) {
    if (!this.socketStore.isConnectWebSocket) {
      return false;
    }
    try {
      const messageData = {
        ...message,
        timestamp: Date.now(),
        userId: this.userStore.userInfo.id
      };
      switch (message.type) {
        case 'comment':
          this.socketStore.sendToAll(JSON.stringify(messageData));
          break;
        case 'like':
        case 'follow':
        case 'mention':
          if (message.data?.receiverId) {
            this.socketStore.sendToUser(
              message.data.receiverId.toString(),
              JSON.stringify(messageData)
            );
          }
          break;
        default:
          this.socketStore.sendToAll(JSON.stringify(messageData));
      }
      return true;
    } catch (error) {
      return false;
    }
  }

  public getConnectionStatus() {
    return {
      isConnected: this.socketStore.isConnectWebSocket,
      reconnectAttempts: this.reconnectAttempts,
      maxReconnectAttempts: this.maxReconnectAttempts
    };
  }

  public reconnect() {
    this.reconnectAttempts = 0;
    this.socketStore.disconnectWebSocket();
    setTimeout(() => {
      this.initWebSocket();
    }, 1000);
  }

  public disconnect() {
    this.socketStore.disconnectWebSocket();
    this.messageHandlers = [];
  }
}

export const notificationService = new NotificationService();
export default notificationService;
